const Router = require('koa-router');
const pool = require('../db');
const router = new Router();

// 记录播放历史
router.post('/history', async (ctx) => {
  try {
    const { user_id, song_id } = ctx.request.body;
    
    if (!user_id || !song_id) {
      ctx.body = { code: -1, message: '用户ID和歌曲ID不能为空' };
      return;
    }
    
    // 检查歌曲是否存在
    const [songs] = await pool.execute('SELECT id FROM songs WHERE id = ?', [song_id]);
    if (songs.length === 0) {
      ctx.body = { code: -1, message: '歌曲不存在' };
      return;
    }
    
    // 插入播放历史记录
    await pool.execute(
      'INSERT INTO play_history (user_id, song_id) VALUES (?, ?)',
      [user_id, song_id]
    );
    
    // 更新歌曲播放次数
    await pool.execute(
      'UPDATE songs SET play_count = play_count + 1 WHERE id = ?',
      [song_id]
    );
    
    ctx.body = {
      code: 0,
      message: '记录播放历史成功'
    };
  } catch (error) {
    console.error('记录播放历史失败:', error);
    ctx.body = { code: -1, message: '记录播放历史失败' };
  }
});

// 获取用户播放历史
router.get('/history/:user_id', async (ctx) => {
  try {
    const { user_id } = ctx.params;
    const { page = 1, limit = 20, days = 30 } = ctx.query;
    const offset = (page - 1) * limit;
    
    // 计算日期范围
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));
    
    const [history] = await pool.execute(`
      SELECT s.*, ph.played_at
      FROM songs s
      JOIN play_history ph ON s.id = ph.song_id
      WHERE ph.user_id = ? AND ph.played_at >= ?
      ORDER BY ph.played_at DESC
      LIMIT ? OFFSET ?
    `, [user_id, startDate, parseInt(limit), offset]);
    
    // 获取总数
    const [countResult] = await pool.execute(
      'SELECT COUNT(*) as total FROM play_history WHERE user_id = ? AND played_at >= ?',
      [user_id, startDate]
    );
    const total = countResult[0].total;
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        history,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    };
  } catch (error) {
    console.error('获取播放历史失败:', error);
    ctx.body = { code: -1, message: '获取播放历史失败' };
  }
});

// 清除播放历史
router.delete('/history/:user_id', async (ctx) => {
  try {
    const { user_id } = ctx.params;
    const { days } = ctx.query;
    
    let sql = 'DELETE FROM play_history WHERE user_id = ?';
    let params = [user_id];
    
    if (days) {
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - parseInt(days));
      sql += ' AND played_at >= ?';
      params.push(startDate);
    }
    
    const [result] = await pool.execute(sql, params);
    
    ctx.body = {
      code: 0,
      message: '清除播放历史成功',
      data: {
        deleted_count: result.affectedRows
      }
    };
  } catch (error) {
    console.error('清除播放历史失败:', error);
    ctx.body = { code: -1, message: '清除播放历史失败' };
  }
});

// 获取播放统计
router.get('/history/:user_id/stats', async (ctx) => {
  try {
    const { user_id } = ctx.params;
    const { days = 30 } = ctx.query;
    
    // 计算日期范围
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));
    
    // 获取总播放次数
    const [totalPlays] = await pool.execute(
      'SELECT COUNT(*) as total FROM play_history WHERE user_id = ? AND played_at >= ?',
      [user_id, startDate]
    );
    
    // 获取播放最多的歌曲
    const [topSongs] = await pool.execute(`
      SELECT s.*, COUNT(*) as play_count
      FROM songs s
      JOIN play_history ph ON s.id = ph.song_id
      WHERE ph.user_id = ? AND ph.played_at >= ?
      GROUP BY s.id
      ORDER BY play_count DESC
      LIMIT 10
    `, [user_id, startDate]);
    
    // 获取播放最多的艺术家
    const [topArtists] = await pool.execute(`
      SELECT s.artist, COUNT(*) as play_count
      FROM songs s
      JOIN play_history ph ON s.id = ph.song_id
      WHERE ph.user_id = ? AND ph.played_at >= ?
      GROUP BY s.artist
      ORDER BY play_count DESC
      LIMIT 10
    `, [user_id, startDate]);
    
    // 获取每日播放统计
    const [dailyStats] = await pool.execute(`
      SELECT DATE(played_at) as date, COUNT(*) as count
      FROM play_history
      WHERE user_id = ? AND played_at >= ?
      GROUP BY DATE(played_at)
      ORDER BY date DESC
      LIMIT 30
    `, [user_id, startDate]);
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        total_plays: totalPlays[0].total,
        top_songs: topSongs,
        top_artists: topArtists,
        daily_stats: dailyStats
      }
    };
  } catch (error) {
    console.error('获取播放统计失败:', error);
    ctx.body = { code: -1, message: '获取播放统计失败' };
  }
});

// 获取最近播放的歌曲
router.get('/history/:user_id/recent', async (ctx) => {
  try {
    const { user_id } = ctx.params;
    const { limit = 10 } = ctx.query;
    
    const [recentSongs] = await pool.execute(`
      SELECT DISTINCT s.*, MAX(ph.played_at) as last_played
      FROM songs s
      JOIN play_history ph ON s.id = ph.song_id
      WHERE ph.user_id = ?
      GROUP BY s.id
      ORDER BY last_played DESC
      LIMIT ?
    `, [user_id, parseInt(limit)]);
    
    ctx.body = {
      code: 0,
      message: 'success',
      data: recentSongs
    };
  } catch (error) {
    console.error('获取最近播放歌曲失败:', error);
    ctx.body = { code: -1, message: '获取最近播放歌曲失败' };
  }
});

module.exports = router;
